package com.chengyu.core.controller.common;

import com.chengyu.core.controller.UserBaseController;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.domain.enums.MemberTypes;
import com.chengyu.core.domain.enums.SecretEnum;
import com.chengyu.core.domain.enums.ThirdEnums;
import com.chengyu.core.domain.result.CustomerConstant;
import com.chengyu.core.entity.CommonResult;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.model.*;
import com.chengyu.core.result.CommonResultCode;
import com.chengyu.core.service.config.ConfigSearchService;
import com.chengyu.core.service.content.*;
import com.chengyu.core.service.floor.FloorGlobalStyleService;
import com.chengyu.core.service.floor.FloorService;
import com.chengyu.core.service.system.BankConfigService;
import com.chengyu.core.service.system.ConfigService;
import com.chengyu.core.service.system.VerifyCodeService;
import com.chengyu.core.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @title  配置管理
 * @author LeGreen
 * @date   2021/1/8
 */
@Api(tags = "配置管理")
@Controller
@RequestMapping("/common")
public class ConfigController extends UserBaseController {

	@Autowired
	private ConfigService configService;
	@Autowired
	private AdvertService advertService;
	@Autowired
	private BannerService bannerService;
	@Autowired
	private AgreementService agreementService;
	@Autowired
	private VerifyCodeService verifyCodeService;
	@Autowired
	private ArticleService articleService;
	@Autowired
	private ArticleCateService articleCateService;
	@Autowired
	private BankConfigService bankConfigService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private ConfigSearchService configSearchService;
	@Autowired
	private FloorService floorService;
	@Autowired
	private FloorGlobalStyleService floorGlobalStyleService;

	@ApiOperation(value = "系统参数列表")
	@ResponseBody
	@RequestMapping(value="/config/getList", method=RequestMethod.GET)
	public CommonResult<Map<String,String>> getConfig() {
		Map<String, String> map = configService.getAllConfigValueMap();
		System.out.println(map);
		return CommonResult.success(map);
	}

	@ApiOperation(value = "首页装修配置")
	@ResponseBody
	@RequestMapping(value="/floor/getList", method=RequestMethod.GET)
	public CommonResult<List<FloorMobilePages>> getFloorList() {
		List<FloorMobilePages> list = floorService.getCurrentIndexFloor();


		List<FloorMobilePages> listNew = list.stream().map(floorMobilePage -> {

			if(floorMobilePage.getModuleKey().equals("notice")){


				List<CmsArticle>  atricles = null;
				try {
					atricles = articleService.getArticleList(99,null,"",1,5);
				} catch (ServiceException e) {
					e.printStackTrace();
				}

				FloorMobilePages floorMobilePagenew  = floorMobilePage;
//						    floorMobilePagenew = floorMobilePage;
				System.out.println("____________________________________________________________atricles________________________________________________________________");
				System.out.println(atricles);
				floorMobilePagenew.setModuleData(com.alibaba.fastjson.JSON.toJSONString(atricles));
				return floorMobilePagenew;
			}

			return floorMobilePage;


		}).collect(Collectors.toList());


		return CommonResult.success(listNew);
	}


	@ApiOperation(value = "专题装修配置")
	@ResponseBody
	@RequestMapping(value="/floor/getListByTemplateId", method=RequestMethod.GET)
	public CommonResult<List<FloorMobilePages>> getListByTemplateId(Integer templateId) {
		List<FloorMobilePages> list = floorService.getFloorMobileDataList(templateId);
		return CommonResult.success(list);

	}


	@ApiOperation(value = "全局样式")
	@ResponseBody
	@RequestMapping(value="/globalStyle/get", method=RequestMethod.GET)
	public CommonResult<Map<String, String>> getGlobalStyle() {
		return CommonResult.success(floorGlobalStyleService.getGlobalStyleByCache());
	}

	@ApiOperation(value = "热门搜索列表")
	@ResponseBody
	@RequestMapping(value="/search/getList", method=RequestMethod.GET)
	public CommonResult<List<ConfigSearch>> getSearch() {
		List<ConfigSearch> list = configSearchService.getTenSearchList();
		return CommonResult.success(list);
	}

	@ApiOperation(value = "轮播图列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "location", value = "位置(1首页)")
	})
	@ResponseBody
	@RequestMapping(value="/banner/getList", method=RequestMethod.GET)
	public CommonResult<List<CmsBanner>> getBanner(String location) throws Exception {
		return CommonResult.success(bannerService.getAllBanners(location));
	}


	@ApiOperation(value = "文章分类")
	@ResponseBody
	@RequestMapping(value="/articleCate/getCateList", method=RequestMethod.GET)
	public CommonResult<List<CmsArticleCate>> getCateList() {
		return CommonResult.success(articleCateService.getAllArticleCates());
	}

	@ApiOperation(value = "文章列表")
	@ResponseBody
	@RequestMapping(value="/article/getList", method=RequestMethod.GET)
	public CommonResult<List<CmsArticle>> getArticleList(Integer cateId, Integer type) throws Exception {
		return CommonResult.success(articleService.getAllArticles(cateId, type));
	}

	@ApiOperation(value = "文章详情")
	@ResponseBody
	@RequestMapping(value="/article/get", method=RequestMethod.GET)
	public CommonResult<CmsArticle> get(Integer articleId) throws Exception {
		return CommonResult.success(articleService.getArticleById(articleId));
	}


	@ApiOperation(value = "公告详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cate", value = "user用户端>>shop商家端")
	})
	@ResponseBody
	@RequestMapping(value="/notice/get", method=RequestMethod.GET)
	public CommonResult<CmsNotice> getNotice(String cate) {
		return CommonResult.success(noticeService.getNoticeByCate(cate));
	}

	@ApiOperation(value = "广告信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "cate", value = "待定")
	})
	@ResponseBody
	@RequestMapping(value="/advert/get", method=RequestMethod.GET)
	public CommonResult<CmsAdvert> getAdvert(String cate) throws Exception {
		return CommonResult.success(advertService.getAdvertByCate(cate));
	}

	@ApiOperation(value = "协议信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "cate", value = "待定")
	})
	@ResponseBody
	@RequestMapping(value="/agreement/get", method=RequestMethod.GET)
	public CommonResult<CmsAgreement> getAgreement(String cate) throws Exception {
		return CommonResult.success(agreementService.getAgreementByCate(cate));
	}

	@ApiOperation(value = "获取银行卡配置")
	@RequestMapping(value = "/getBankSelector", method = RequestMethod.GET)
	@ResponseBody
	public CommonResult<List<SysBankConfig>> getBankList() throws ServiceException{
		return CommonResult.success(bankConfigService.getBankList());
	}

	@ApiOperation(value = "获取密保问题")
	@ResponseBody
	@RequestMapping(value="/secret/getList", method=RequestMethod.GET)
	public CommonResult<List<Map<String, String>>> getSecretList() {
		List<Map<String, String>> list = new ArrayList<>();
		for(SecretEnum secretEnum : SecretEnum.values()){
			Map<String, String> map = new HashMap<>();
			map.put("key", secretEnum.getKey());
			map.put("question", secretEnum.getQuestion());
			list.add(map);
		}
		return CommonResult.success(list);
	}

	@ApiOperation(value = "上传图片")
	@ResponseBody
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	public CommonResult<Map<String,Object>> upload(MultipartHttpServletRequest request) throws Exception {
		System.out.println(request);
		Map<String, MultipartFile> fileMap = request.getFileMap();
		System.out.println("fileMap"+fileMap);
		if(fileMap.size() <= 0) {
			return CommonResult.success(null);
		}

		Map<String,Object> result = new HashMap<>(16);
		for(String field : fileMap.keySet()) {
			MultipartFile file = fileMap.get(field);
			if(file == null || file.getSize() <= 0 || StringUtils.isBlank(file.getOriginalFilename())) {
				continue;
			}

			long currentTime = System.currentTimeMillis();
			System.out.println("file");
			System.out.println(file);
			System.out.println(file.getOriginalFilename());


			System.out.println(file.getOriginalFilename().lastIndexOf("."));


			String fileName;
			if(file.getOriginalFilename().lastIndexOf(".")==-1){
				fileName = currentTime + "" + file.getOriginalFilename();

			}else{
				fileName = currentTime + "" + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			}

			String imgUrl = thirdManager.getThidFactory(this.getThirdMod(ThirdEnums.UPLOAD.getKey())).upload(file, fileName, CommonConstant.IMG);
			result.put("imgUrl", imgUrl);

			break;
		}

		return CommonResult.success(result);
	}

//	@ApiOperation(value = "上传图片bas64")
//	@ResponseBody
//	@RequestMapping(value="/uploadbase64", method=RequestMethod.POST)
//	public CommonResult<Map<String,Object>> uploadFile(MultipartHttpServletRequest request) throws Exception {
//		Map<String, MultipartFile> fileMap = request.getFileMap();
//		if(fileMap.size() <= 0) {
//			return CommonResult.success(null);
//		}
//
//		Map<String,Object> result = new HashMap<>(16);
//		for(String field : fileMap.keySet()) {
//			MultipartFile file = fileMap.get(field);
//			if(file == null || file.getSize() <= 0 || StringUtils.isBlank(file.getOriginalFilename())) {
//				continue;
//			}
//
//			long currentTime = System.currentTimeMillis();
//			String fileName = currentTime + "" + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//			String imgUrl = thirdManager.getThidFactory(this.getThirdMod(ThirdEnums.UPLOAD.getKey())).upload(file, fileName, CommonConstant.IMG);
//			result.put("imgUrl", imgUrl);
//
//			break;
//		}
//
//		return CommonResult.success(result);
//	}
//	@ApiOperation("base64图片上传")
//	@PostMapping("/base64Upload")
//	public Result<Object> uploadImage(String base64Data){
//		String dataPrix = ""; //base64格式前头
//		String data = "";//实体部分数据
//		if(base64Data==null||"".equals(base64Data)){
//			return Result.error("上传失败，上传图片数据为空");
//		}else {
//			String [] d = base64Data.split("base64,");//将字符串分成数组
//			if(d != null && d.length == 2){
//				dataPrix = d[0];
//				data = d[1];
//			}else {
//				return Result.error("上传失败，数据不合法");
//			}
//		}
//		String suffix = "";//图片后缀，用以识别哪种格式数据
//		//编码的jpeg图片数据
//		if("data:image/jpg;".equalsIgnoreCase(dataPrix)){
//			suffix = ".jpg";
//		}else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){
//			//编码的icon图片数据
//			suffix = ".ico";
//		} else if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){
//			//编码的icon图片数据
//			suffix = ".jpeg";
//		}else if("data:image/gif;".equalsIgnoreCase(dataPrix)){
//			//编码的gif图片数据
//			suffix = ".gif";
//		}else if("data:image/png;".equalsIgnoreCase(dataPrix)){
//			//编码的png图片数据
//			suffix = ".png";
//		}else {
//			return Result.error("上传图片格式不合法");
//		}
//		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//		String tempFileName=uuid+suffix;
//		String imgFilePath = UPLOAD_FOLDER+tempFileName;//新生成的图片
//		BASE64Decoder decoder = new BASE64Decoder();
//		try {
//			String replace = base64Data.replace(" ", "+");//这一句必须加，要不然写入图片会错误。
//			String[] baseStrs = replace.split(",");
//			byte[] b = new byte[0];
//			b = decoder.decodeBuffer(baseStrs[1]);
//			for (int i = 0; i < b.length; ++i) {
//				if (b[i] < 0) {
//					b[i] += 256;
//				}
//			}
//			OutputStream out = new FileOutputStream(imgFilePath);
//			out.write(b);
//			out.flush();
//			out.close();
//			String imgurl=UPLOAD_FOLDER+tempFileName;
//			//imageService.save(imgurl);
//			return Result.success(imgurl);
//		} catch (IOException e) {
//			e.printStackTrace();
//			return Result.error("上传图片失败");
//		}
//
//	}

    @ApiOperation(value = "上传视频")
    @RequestMapping(value="/uploadVideo", method=RequestMethod.POST)
    @ResponseBody
    public CommonResult<Map<String,Object>> uploadVideo(MultipartHttpServletRequest request) throws Exception {
		Map<String, MultipartFile> fileMap = request.getFileMap();
		if(fileMap.size() <= 0) {
			return CommonResult.success(null);
		}

		Map<String,Object> result = new HashMap<>(16);
		for(String field : fileMap.keySet()) {
			MultipartFile file = fileMap.get(field);
			if(file == null || file.getSize() <= 0 || StringUtils.isBlank(file.getOriginalFilename())) {
				continue;
			}

			long currentTime = System.currentTimeMillis();
			String fileName = currentTime + ".mp4";
			String imgUrl = thirdManager.getThidFactory(this.getThirdMod(ThirdEnums.UPLOAD.getKey())).upload(file, fileName, CommonConstant.VIDEO);
			result.put("videoUrl", imgUrl);

			break;
		}
		return CommonResult.success(result);
	}

    @ApiOperation(value = "发送验证码")
    @ApiImplicitParams({
		@ApiImplicitParam(name = "phone", value = "手机"),
		@ApiImplicitParam(name = "sendType", value = "发送类型(1注册 2绑定 3忘记密码 4通用)"),
		@ApiImplicitParam(name = "cToken", value = "图形验证码TOKEN"),
		@ApiImplicitParam(name = "captcha", value = "图形验证码")
	})
    @ResponseBody
	@RequestMapping(value={"/sendCode"}, method=RequestMethod.POST)
	public CommonResult<String> sendCode(String phone, String sendType, String cToken, String captcha) throws ServiceException {
		if(StringUtils.isEmpty(sendType)) {
			sendType = "1";
		}

		if("1".equals(sendType)){
			//校验图形验证码
			super.validateCaptcha(cToken, captcha);

			//注册
			UmsMember phoneMember = memberService.getMemberByParams(phone, MemberTypes.PHONE);
			if(phoneMember != null){
				return CommonResult.failed( "该手机号已注册，请重新填写手机号！");
			}
		}else if("3".equals(sendType)){
			//忘记密码
			UmsMember phoneMember = memberService.getMemberByParams(phone, MemberTypes.PHONE);
			if(phoneMember == null){
				return CommonResult.failed( "该手机号不存在，请重新填写手机号！");
			}
		}

		Map<String,String> templateParam = new HashMap<>(16);
		try {
			verifyCodeService.sendSms(phone, sendType, templateParam);
			return CommonResult.success("发送成功");
		} catch (ServiceException e) {
			return CommonResult.failed( e.getMessage());
//			throw new ServiceException(e.getMessage());

		}

//		return CommonResult.success(null);
	}

    @ApiOperation(value = "校验验证码")
    @ApiImplicitParams({
		@ApiImplicitParam(name = "phone", value = "手机"),
		@ApiImplicitParam(name = "code", value = "验证码")
	})
    @ResponseBody
	@RequestMapping(value={"/validateCode"}, method=RequestMethod.POST)
	public CommonResult<String> validateCode(String phone, String code) throws Exception {
		//校验短信验证码
    	verifyCodeService.validateCode(phone, code);
    	return CommonResult.success(null);
	}

	@ApiOperation(value = "获取人工客服和智能客服的ID")
	@ResponseBody
	@RequestMapping(value="/chat/getCustomerId", method=RequestMethod.GET)
	public CommonResult<Map<String,Object>> getCustomerId() {
		Map<String,Object> result = new HashMap<>();
		result.put("customerMemberId", CustomerConstant.MEMBER_ID);
		result.put("customerAdminId", CustomerConstant.ADMIN_MEMBER_ID);
		return CommonResult.success(result);
	}
}
